// 统一处理所有http请求和响应
import axios from 'axios'

const baseUrl = '/xpyApp'

// 暴露出ajax函数
export default {
  post(url, data) {
    return axios({
      method: 'post',
      url: baseUrl + url,
      data,
      // 在数据提交前对数据进行处理
      transformRequest: [
        function(data) {
          let ret = ''
          for (const it in data) {
            if (data[it] === null || data[it] === undefined) {
              data[it] = ''
            }
            ret += `${encodeURIComponent(it)}=${encodeURIComponent(data[it])}&`
          }
          return ret.slice(0, -1)
        }
      ],
      timeout: 50000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).catch(error => {
      console.log(error.message)
    })
  },
  get(url, params) {
    return axios({
      method: 'get',
      url: baseUrl + url,
      params, // get 请求时带的参数
      timeout: 50000,
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    })
  }
}
